<template>
  <div class="profile-container">
    <div class="profile-card">
      <!-- 页面头部 -->
      <div class="profile-header">
        <div class="header-content">
          <div class="avatar-section">
            <div class="avatar-wrapper">
              <el-avatar :size="80" :src="userInfo.avatar">
                {{ userInfo.nickname?.charAt(0)?.toUpperCase() || userInfo.username?.charAt(0)?.toUpperCase() }}
              </el-avatar>
              <div v-if="isEditing" class="avatar-edit" @click="triggerFileInput">
                <el-icon><Camera /></el-icon>
                <span>更换头像</span>
                <input 
                  type="file" 
                  ref="fileInput" 
                  style="display: none;" 
                  accept="image/*"
                  @change="handleFileChange"
                />
              </div>
            </div>
            <div class="user-title">
              <h2>{{ userInfo.username }}</h2>
              <div class="user-tags">
                <el-tag :type="getRoleTagType(userInfo.roleType)" size="small" class="role-tag">
                  {{ getRoleName(userInfo.roleType) }}
                </el-tag>
                <el-tag :type="userInfo.status === 1 ? 'success' : 'info'" size="small">
                  {{ userInfo.statusName }}
                </el-tag>
              </div>
            </div>
          </div>
          <div class="header-actions">
            <el-button 
              type="primary" 
              :icon="isEditing ? 'Close' : 'Edit'"
              @click="toggleEdit"
            >
              {{ isEditing ? '取消编辑' : '修改信息' }}
            </el-button>
            <el-button 
              @click="handleClose"
              icon="Back"
            >
              返回
            </el-button>
          </div>
        </div>
      </div>

      <!-- 查看模式 -->
      <div v-if="!isEditing" class="info-section">
        <el-row :gutter="40">
          <el-col :span="12">
            <div class="info-card">
              <h3>基本信息</h3>
              <div class="info-list">
                <div class="info-item">
                  <el-icon><User /></el-icon>
                  <span class="label">用户名</span>
                  <span class="value">{{ userInfo.username }}</span>
                </div>
                <div class="info-item">
                  <el-icon><ChatDotRound /></el-icon>
                  <span class="label">昵称</span>
                  <span class="value">{{ userInfo.nickname || '-' }}</span>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-card">
              <h3>联系方式</h3>
              <div class="info-list">
                <div class="info-item">
                  <el-icon><Message /></el-icon>
                  <span class="label">邮箱</span>
                  <span class="value">{{ userInfo.email || '-' }}</span>
                </div>
                <div class="info-item">
                  <el-icon><Iphone /></el-icon>
                  <span class="label">手机号</span>
                  <span class="value">{{ userInfo.phone || '-' }}</span>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 编辑模式 -->
      <div v-else class="edit-section">
        <el-form 
          ref="formRef" 
          :model="form" 
          :rules="rules" 
          label-width="100px"
          class="edit-form"
        >
          <el-row :gutter="40">
            <el-col :span="12">
              <div class="form-section">
                <h3>基本信息</h3>
                <el-form-item label="昵称" prop="nickname">
                  <el-input 
                    v-model="form.nickname" 
                    placeholder="请输入昵称"
                    prefix-icon="User"
                  />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input 
                    v-model="form.email" 
                    placeholder="请输入邮箱"
                    prefix-icon="Message"
                  />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input 
                    v-model="form.phone" 
                    placeholder="请输入手机号"
                    prefix-icon="Iphone"
                  />
                </el-form-item>
                
                <!-- 显示已上传的头像预览 -->
                <el-form-item v-if="form.avatar || imageUrl" label="头像预览">
                  <div class="avatar-preview">
                    <el-image 
                      :src="imageUrl || form.avatar" 
                      fit="cover"
                      style="width: 100px; height: 100px; border-radius: 8px;"
                    />
                    <el-button type="danger" size="small" icon="Delete" @click="removeAvatar" class="remove-btn">
                      移除头像
                    </el-button>
                  </div>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="form-section">
                <h3>修改密码</h3>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input 
                    v-model="form.newPassword" 
                    type="password" 
                    placeholder="请输入新密码"
                    prefix-icon="Lock"
                    show-password 
                  />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input 
                    v-model="form.confirmPassword" 
                    type="password" 
                    placeholder="请确认新密码"
                    prefix-icon="Key"
                    show-password 
                  />
                </el-form-item>
              </div>
            </el-col>
          </el-row>

          <div class="form-actions">
            <el-button type="primary" @click="submitForm" :loading="loading">
              保存修改
            </el-button>
            <el-button @click="toggleEdit">取消</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { getUserInfo, updateUserInfo } from '@/api/user'
import { upload } from '@/api/common'
import {
  User,
  Message,
  Iphone,
  Lock,
  Key,
  ChatDotRound,
  Edit,
  Close,
  Back,
  Camera,
  Delete
} from '@element-plus/icons-vue'

const router = useRouter()
const isEditing = ref(false)
const loading = ref(false)
const formRef = ref(null)
const fileInput = ref(null)
const userInfo = ref({})
const imageUrl = ref('')
const avatarFile = ref(null)

const getRoleName = (roleType) => {
  switch (roleType) {
    case 1:
      return '系统管理员'
    case 2:
      return '广告用户'
    case 3:
      return '设备拥有机构'
    default:
      return '未知角色'
  }
}

const getRoleTagType = (roleType) => {
  switch (roleType) {
    case 1:
      return 'danger'  // 管理员用红色
    case 2:
      return 'warning' // 广告用户用黄色
    case 3:
      return 'success' // 设备机构用绿色
    default:
      return 'info'
  }
}

// 表单数据
const form = reactive({
  nickname: '',
  email: '',
  phone: '',
  newPassword: '',
  confirmPassword: '',
  avatar: ''
})

// 表单验证规则
const rules = {
  nickname: [
    { max: 20, message: '昵称长度不能超过20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  newPassword: [
    { min: 6, max: 20, message: '密码长度在6-20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    {
      validator: (rule, value, callback) => {
        if (form.newPassword && value !== form.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const { data } = await getUserInfo()
    if (data.code === 200) {
      userInfo.value = data.data
    } else {
      ElMessage.error(data.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败，请重试')
  }
}

// 切换编辑模式
const toggleEdit = () => {
  isEditing.value = !isEditing.value
  if (isEditing.value) {
    form.nickname = userInfo.value.nickname || ''
    form.email = userInfo.value.email || ''
    form.phone = userInfo.value.phone || ''
    form.avatar = userInfo.value.avatar || ''
    form.newPassword = ''
    form.confirmPassword = ''
    imageUrl.value = ''
    avatarFile.value = null
  }
}

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click()
}

// 处理文件选择
const handleFileChange = (e) => {
  const file = e.target.files[0]
  if (!file) return
  
  // 验证文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('请选择图片文件')
    return
  }
  
  // 验证文件大小（2MB限制）
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB')
    return
  }
  
  // 保存文件引用
  avatarFile.value = file
  
  // 创建预览URL
  imageUrl.value = URL.createObjectURL(file)
}

// 移除头像
const removeAvatar = () => {
  imageUrl.value = ''
  avatarFile.value = null
  form.avatar = ''
}

// 上传头像
const uploadAvatar = async () => {
  if (!avatarFile.value) return form.avatar
  
  const loadingInstance = ElLoading.service({
    text: '正在上传头像...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    const formData = new FormData()
    formData.append('file', avatarFile.value)
    formData.append('path', 'avatar')
    
    const { data } = await upload(formData)
    loadingInstance.close()
    
    if (data.code === 200) {
      ElMessage.success('头像上传成功')
      return data.data
    } else {
      ElMessage.error(data.message || '头像上传失败')
      return form.avatar
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败，请重试')
    return form.avatar
  } finally {
    loadingInstance.close()
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 如果选择了新头像，先上传
    let avatarUrl = form.avatar
    if (avatarFile.value) {
      avatarUrl = await uploadAvatar()
    }
    
    const payload = {
      nickname: form.nickname,
      email: form.email,
      phone: form.phone,
      avatar: avatarUrl
    }

    if (form.newPassword) {
      payload.newPassword = form.newPassword
      payload.confirmPassword = form.confirmPassword
    }

    const { data } = await updateUserInfo(payload)
    if (data.code === 200) {
      ElMessage.success('修改成功')
      await fetchUserInfo()
      isEditing.value = false
    } else {
      ElMessage.error(data.message || '修改失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败，请检查表单内容')
  } finally {
    loading.value = false
  }
}

// 处理关闭
const handleClose = async () => {
  if (isEditing.value) {
    try {
      await ElMessageBox.confirm(
        '有未保存的修改，确定要离开吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      router.back()
    } catch {
      // 用户取消关闭
    }
  } else {
    router.back()
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
/* 修改容器样式，实现全屏效果 */
.profile-container {
  padding: 0;
  background: #f0f2f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.profile-card {
  flex: 1;
  background: #fff;
  border-radius: 0;
  box-shadow: none;
  display: flex;
  flex-direction: column;
}

/* 优化头部样式 */
.profile-header {
  background: linear-gradient(135deg, #1890ff 0%, #1d39c4 100%);
  padding: 32px 48px;
  color: #fff;
  position: relative;
}

.profile-header::after {
  content: '';
  position: absolute;
  bottom: -50px;
  left: 0;
  right: 0;
  height: 50px;
  background: inherit;
  filter: blur(20px);
  opacity: 0.3;
}

.header-content {
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

/* 头像样式增强 */
.avatar-wrapper {
  position: relative;
}

:deep(.el-avatar) {
  width: 80px;
  height: 80px;
  font-size: 24px;
  border: 2px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.avatar-edit {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s;
  cursor: pointer;
}

.avatar-edit:hover {
  opacity: 1;
}

.avatar-edit .el-icon {
  font-size: 20px;
  margin-bottom: 4px;
}

.avatar-preview {
  display: flex;
  align-items: center;
  gap: 16px;
}

.remove-btn {
  height: 36px;
}

.user-title {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-title h2 {
  margin: 0;
  font-size: 24px;
  color: #fff;
  font-weight: 500;
  letter-spacing: 0.5px;
}

/* 优化内容区域样式 */
.info-section {
  flex: 1;
  padding: 64px;
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
}

.info-card {
  background: #fff;
  border-radius: 12px;
  padding: 32px;
  height: 100%;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #eee;
  transition: all 0.3s ease;
}

.info-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.info-card h3 {
  margin: 0 0 24px 0;
  color: #1890ff;
  font-size: 20px;
  font-weight: 600;
  position: relative;
  padding-left: 16px;
}

.info-card h3::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background: #1890ff;
  border-radius: 2px;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.info-item:hover {
  background: #f0f7ff;
}

.info-item .el-icon {
  font-size: 24px;
  color: #1890ff;
  background: rgba(24, 144, 255, 0.1);
  padding: 8px;
  border-radius: 8px;
}

.label {
  color: #666;
  min-width: 80px;
  font-size: 15px;
}

.value {
  color: #333;
  font-weight: 500;
  font-size: 15px;
  flex: 1;
}

/* 优化编辑模式样式 */
.edit-section {
  flex: 1;
  padding: 64px;
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
}

.form-section {
  background: #fff;
  border-radius: 12px;
  padding: 32px;
  margin-bottom: 32px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #eee;
}

.form-section h3 {
  margin: 0 0 24px 0;
  color: #1890ff;
  font-size: 20px;
  font-weight: 600;
  position: relative;
  padding-left: 16px;
}

.form-section h3::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background: #1890ff;
  border-radius: 2px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 48px;
}

:deep(.el-button) {
  padding: 12px 24px;
  font-size: 15px;
}

:deep(.el-input__wrapper) {
  padding: 8px 16px;
  box-shadow: 0 0 0 1px #dcdfe6;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #1890ff;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  font-size: 15px;
}

/* 用户标签样式 */
.user-tags {
  display: flex;
  gap: 8px;
  align-items: center;
}

.role-tag {
  font-weight: 500;
}

/* 标签样式优化 */
:deep(.el-tag) {
  border: none;
  padding: 4px 8px;
}

:deep(.el-tag--danger) {
  background-color: rgba(245, 108, 108, 0.2);
  color: #fff;
}

:deep(.el-tag--warning) {
  background-color: rgba(230, 162, 60, 0.2);
  color: #fff;
}

:deep(.el-tag--success) {
  background-color: rgba(103, 194, 58, 0.2);
  color: #fff;
}

:deep(.el-tag--info) {
  background-color: rgba(255, 255, 255, 0.2);
  color: #fff;
}

/* 响应式布局优化 */
@media (max-width: 1200px) {
  .profile-header {
    padding: 32px;
  }

  .info-section,
  .edit-section {
    padding: 32px;
  }
}

@media (max-width: 768px) {
  .profile-header {
    padding: 20px;
  }

  .header-content {
    flex-direction: column;
    gap: 24px;
    text-align: center;
  }

  .avatar-section {
    flex-direction: column;
    gap: 16px;
  }

  .user-title h2 {
    font-size: 20px;
  }

  .user-tags {
    justify-content: center;
  }

  .info-section,
  .edit-section {
    padding: 16px;
  }

  .info-card,
  .form-section {
    padding: 20px;
  }

  .el-row {
    margin: 0 !important;
  }

  .el-col {
    padding: 0 !important;
  }
  
  .avatar-preview {
    flex-direction: column;
    align-items: center;
  }
}
</style>